package com.example.tasktimer

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.tasktimer.ui.theme.TaskTimerTheme
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField

import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.border
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.material3.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.geometry.Offset
import androidx.compose.foundation.Canvas
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.filled.Build

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            RegexRedosScreen()
        }
    }
}

@Composable
fun RegexRedosScreen() {
    var regex by remember { mutableStateOf("") }
    var result by remember { mutableStateOf<ResultData?>(null) }
    var showSettings by remember { mutableStateOf(false) }
    var attackCount by remember { mutableStateOf(10) }
    var timeout by remember { mutableStateOf(2000) }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            OutlinedTextField(
                value = regex,
                onValueChange = { regex = it },
                label = { Text("请输入正则表达式") },
                modifier = Modifier.weight(1f),
                trailingIcon = {
                    Row {
                        IconButton(onClick = {
                            // 死数据模拟检测
                            val fakeTimes = listOf(120, 180, 210, 250, 90, 60, 300, 220, 150, 80)
                            val matchCount = fakeTimes.size
                            val matchSuccessCount = 8
                            val matchFailCount = 2
                            val avg = if (fakeTimes.isNotEmpty()) fakeTimes.sum() / fakeTimes.size else 0
                            val max = fakeTimes.maxOrNull() ?: 0
                            val min = fakeTimes.minOrNull() ?: 0
                            val median = if (fakeTimes.isNotEmpty()) fakeTimes.sorted().let { s ->
                                if (s.size % 2 == 1) s[s.size/2] else (s[s.size/2-1] + s[s.size/2])/2
                            } else 0
                            val timeoutCount = fakeTimes.count { it > 200 }
                            result = if (regex.contains("(a+)+")) {
                                ResultData(
                                    safe = false,
                                    attackString = "aaaaaaaaaaaaaaaa!",
                                    memory = 120L * 1024 * 1024, // 120MB
                                    cpu = "80%",
                                    totalTime = fakeTimes.sum(),
                                    matchTimeoutCount = timeoutCount,
                                    matchCount = matchCount,
                                    matchSuccessCount = matchSuccessCount,
                                    matchFailCount = matchFailCount,
                                    avgMatchTime = avg,
                                    maxMatchTime = max,
                                    minMatchTime = min,
                                    medianMatchTime = median,
                                    matchTimeDistribution = fakeTimes
                                )
                            } else {
                                ResultData(safe = true)
                            }
                        }) {
                            Icon(Icons.Filled.PlayArrow, contentDescription = "开始测试")
                        }
                        IconButton(onClick = { showSettings = true }) {
                            Icon(Icons.Filled.Settings, contentDescription = "设置")
                        }
                    }
                }
            )
        }

        Spacer(modifier = Modifier.height(32.dp))

        result?.let {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                if (it.safe) {
                    // 安全提示卡片
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(60.dp)
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(Color(0xFF4CAF50), Color(0xFF81C784))
                                ),
                                shape = RoundedCornerShape(16.dp)
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "正则表达式安全 ✓",
                            color = Color.White,
                            fontSize = 20.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }
                } else {
                    // 风险提示卡片
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(60.dp)
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(Color(0xFFE53935), Color(0xFFEF5350))
                                ),
                                shape = RoundedCornerShape(16.dp)
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "${regex} 有风险 ⚠️",
                            color = Color.White,
                            fontSize = 20.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }

                    // 攻击字符串卡片
                    ElevatedCard(
                        colors = CardDefaults.cardColors(containerColor = Color(0xFFFFEBEE)),
                        shape = RoundedCornerShape(16.dp),
                        modifier = Modifier.fillMaxWidth(),
                        elevation = CardDefaults.elevatedCardElevation(defaultElevation = 4.dp)
                    ) {
                        Column(Modifier.padding(20.dp)) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Icon(Icons.Filled.Build, contentDescription = null, tint = Color.Red)
                                Spacer(modifier = Modifier.width(8.dp))
                                Text("攻击字符串", color = Color.Red, fontWeight = FontWeight.Bold, fontSize = 16.sp)
                            }
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = it.attackString,
                                fontSize = 16.sp,
                                color = Color(0xFF424242),
                                modifier = Modifier
                                    .background(Color(0xFFF5F5F5), RoundedCornerShape(8.dp))
                                    .padding(12.dp)
                                    .fillMaxWidth()
                            )
                        }
                    }

                    // 性能数据网格卡片
                    ElevatedCard(
                        colors = CardDefaults.cardColors(containerColor = Color.White),
                        shape = RoundedCornerShape(16.dp),
                        modifier = Modifier.fillMaxWidth(),
                        elevation = CardDefaults.elevatedCardElevation(defaultElevation = 4.dp)
                    ) {
                        Column(Modifier.padding(20.dp)) {
                            Text("性能指标", color = Color(0xFF1976D2), fontWeight = FontWeight.Bold, fontSize = 18.sp)
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            // 第一行：内存、CPU、总用时
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                PerformanceCard(
                                    icon = Icons.Filled.Build,
                                    title = "内存占用",
                                    value = "${String.format("%.1f", it.memory.toFloat() / (1024 * 1024))}MB",
                                    color = Color(0xFF9C27B0)
                                )
                                PerformanceCard(
                                    icon = Icons.Filled.Build,
                                    title = "CPU占用",
                                    value = it.cpu,
                                    color = Color(0xFFFF9800)
                                )
                                PerformanceCard(
                                    icon = Icons.Filled.Build,
                                    title = "总用时",
                                    value = "${it.totalTime}ms",
                                    color = Color(0xFFF44336)
                                )
                            }
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            // 第二行：匹配统计
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                PerformanceCard(
                                    icon = Icons.Filled.CheckCircle,
                                    title = "匹配成功",
                                    value = "${it.matchSuccessCount}次",
                                    color = Color(0xFF4CAF50)
                                )
                                PerformanceCard(
                                    icon = Icons.Filled.Build,
                                    title = "匹配失败",
                                    value = "${it.matchFailCount}次",
                                    color = Color(0xFFE91E63)
                                )
                                PerformanceCard(
                                    icon = Icons.Filled.Build,
                                    title = "平均耗时",
                                    value = "${it.avgMatchTime}ms",
                                    color = Color(0xFF607D8B)
                                )
                            }
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            // 时长分布
                            Text("匹配时长分布", fontWeight = FontWeight.Medium, fontSize = 16.sp)
                            Spacer(modifier = Modifier.height(8.dp))
                            val less50 = it.matchTimeDistribution.count { t -> t < 50 }
                            val between50_200 = it.matchTimeDistribution.count { t -> t in 50..200 }
                            val more200 = it.matchTimeDistribution.count { t -> t > 200 }
                            
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                TimeDistributionCard("<50ms", less50, Color(0xFF4CAF50))
                                TimeDistributionCard("50-200ms", between50_200, Color(0xFFFF9800))
                                TimeDistributionCard(">200ms", more200, Color(0xFFF44336))
                            }
                        }
                    }
                }
            }
        }
    }

    if (showSettings) {
        SettingsDialog(
            attackCount = attackCount,
            timeout = timeout,
            onDismiss = { showSettings = false },
            onConfirm = { newCount, newTimeout ->
                attackCount = newCount
                timeout = newTimeout
                showSettings = false
            }
        )
    }
}

data class ResultData(
    val safe: Boolean,
    val attackString: String = "",
    val memory: Long = 0L, // 单位Byte
    val cpu: String = "",
    val totalTime: Int = 0, // ms
    val matchTimeoutCount: Int = 0,
    val matchCount: Int = 0,
    val matchSuccessCount: Int = 0,
    val matchFailCount: Int = 0,
    val avgMatchTime: Int = 0, // ms
    val maxMatchTime: Int = 0, // ms
    val minMatchTime: Int = 0, // ms
    val medianMatchTime: Int = 0, // ms
    val matchTimeDistribution: List<Int> = emptyList() // 每次匹配耗时
)

@Composable
fun MatchTimeBarChart(times: List<Int>) {
    val max = times.maxOrNull() ?: 1
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(40.dp),
        verticalAlignment = Alignment.Bottom
    ) {
        times.forEach { t ->
            Box(
                modifier = Modifier
                    .weight(1f)
                    .height((t * 30 / max).dp)
                    .background(Color(0xFF90CAF9), RoundedCornerShape(2.dp))
            )
            Spacer(modifier = Modifier.width(2.dp))
        }
    }
}

@Composable
fun SettingsDialog(
    attackCount: Int,
    timeout: Int,
    onDismiss: () -> Unit,
    onConfirm: (Int, Int) -> Unit
) {
    var count by remember { mutableStateOf(attackCount.toString()) }
    var time by remember { mutableStateOf(timeout.toString()) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("设置") },
        text = {
            Column {
                OutlinedTextField(
                    value = count,
                    onValueChange = { count = it },
                    label = { Text("攻击次数") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                )
                Spacer(modifier = Modifier.height(16.dp))
                OutlinedTextField(
                    value = time,
                    onValueChange = { time = it },
                    label = { Text("超时时间(ms)") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                )
            }
        },
        confirmButton = {
            Button(onClick = {
                onConfirm(count.toIntOrNull() ?: attackCount, time.toIntOrNull() ?: timeout)
            }) {
                Text("确定")
            }
        },
        dismissButton = {
            OutlinedButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

@Composable
fun PerformanceCard(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    value: String,
    color: Color
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .background(color.copy(alpha = 0.1f), RoundedCornerShape(12.dp))
            .padding(12.dp)
            .width(100.dp)
    ) {
        Icon(icon, contentDescription = null, tint = color, modifier = Modifier.size(24.dp))
        Spacer(modifier = Modifier.height(4.dp))
        Text(title, fontSize = 12.sp, color = Color(0xFF666666))
        Text(value, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = color)
    }
}

@Composable
fun TimeDistributionCard(
    label: String,
    count: Int,
    color: Color
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .background(color.copy(alpha = 0.1f), RoundedCornerShape(8.dp))
            .padding(12.dp)
    ) {
        Text(label, fontSize = 12.sp, color = Color(0xFF666666))
        Text("${count}次", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = color)
    }
}